package com.example.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.course.dto.admin.AdminUpdateUserDo;
import com.example.course.dto.admin.AdminUserListDto;
import com.example.course.dto.admin.AdminUserRemoveDto;
import com.example.course.dto.admin.AdminUserSaveDto;
import com.example.course.dto.user.UserLoginDto;
import com.example.course.mapper.AdminMapper;
import com.example.course.pojo.Admin;
import com.example.course.pojo.User;
import com.example.course.service.UserService;
import com.example.course.mapper.UserMapper;
import com.example.course.utils.common.enums.Code;
import com.example.course.utils.common.enums.Jwt;
import com.example.course.utils.common.enums.Message;
import com.example.course.utils.common.result.PageResponseResult;
import com.example.course.utils.common.result.Result;
import com.example.course.utils.config.BaseContext;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
* @author 24354
* @description 针对表【user】的数据库操作Service实现
* @createDate 2024-03-15 20:06:10
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Result login(UserLoginDto dto) {
        //异常抛出
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        //用户校检
        User checkUser = userMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getUserName, dto.getUsername())
                .or().eq(User::getStudentId, dto.getUsername()));
        String password=checkUser.getUserSalt()+dto.getPassword();
        password = DigestUtils.md5Hex(password);
        if (!checkUser.getUserPassword().equals(password)) {
            return Result.errorResult(Code.LOGIN_PASSWORD_ERROR);
        }
        //创建令牌
        String token = Jwts.builder()
                .setHeaderParam(Message.Jwt_Alg, Jwt.User_Jwt_Key.getAlg())
                .setHeaderParam(Message.Jwt_Typ, Jwt.User_Jwt_Key.getTyp())
                .setSubject(Jwt.User_Jwt_Key.getName())
                .setExpiration(new Date(System.currentTimeMillis() + Jwt.User_Jwt_Key.getExp()))
                .claim(Message.User_Id,checkUser.getUserId())
                .signWith(SignatureAlgorithm.HS256, Jwt.User_Jwt_Key.getKey())
                .compact();
        return Result.okResult(token);
    }

    @Override
    public Result saveUser(AdminUserSaveDto dto) {
        //异常抛出
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        //确认管理员
        Long userId = BaseContext.getCurrentId();
        Admin checkUser = adminMapper.selectById(userId);
        if (userId==null||checkUser==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //是否有重复
        List<User> checkNewUser = userMapper.selectList(Wrappers.<User>lambdaQuery()
                .eq(User::getUserName, dto.getName())
                .or().eq(User::getUserNick, dto.getNick())
                .or().eq(User::getStudentId, dto.getStudentId()));
        if (!CollectionUtils.isEmpty(checkNewUser)||checkNewUser.size()>0) {
            return Result.errorResult(Code.DATA_EXIST);
        }
        //构建实体
        User user=new User();
        user.setUserName(dto.getName());
        user.setUserNick(dto.getNick());
        user.setUserSalt(checkUser.getAdminName());
        user.setPassword(dto.getPassword());
        user.setUserPassword(DigestUtils.md5Hex(checkUser.getAdminName()+dto.getPassword()));
        user.setStudentId(dto.getStudentId());
        //添加
        int check = userMapper.insert(user);
        //异常抛出
        if (check==0) {
            return Result.errorResult(Code.SERVER_ERROR);
        }

        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result getUserList(AdminUserListDto dto) {
        //token脚尖
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //分页重置
        dto.checkParam();
        //分页构建
        IPage page=new Page(dto.getPage(),dto.getSize());
        //获取数据
        LambdaQueryWrapper<User> wrapper=new LambdaQueryWrapper<>();
        //搜索实现
        if (dto.getMemo()!=null) {
            wrapper.like(User::getStudentId,dto.getMemo());
            wrapper.or().like(User::getUserName,dto.getMemo());
        }
        //列表顺序
        wrapper.orderByDesc(User::getUserId);
        //注入分页组件
        page=page(page,wrapper);
        Result result=new PageResponseResult(dto.getPage(),dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    @Override
    public Result removeUser(AdminUserRemoveDto dto) {
        //空值抛出
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        //token校验
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //校验用户
        User check = userMapper.selectById(dto.getId());
        if (check==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        //删除
        int checkRemove = userMapper.deleteById(dto.getId());
        //删除抛出
        if (checkRemove==0) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }

    @Override
    public Result updateUser(AdminUpdateUserDo dto) {
        //空值抛出
        if (dto==null) {
            return Result.errorResult(Code.PARAM_REQUIRE);
        }
        //token校验
        if (BaseContext.getCurrentId()==null) {
            return Result.errorResult(Code.NEED_LOGIN);
        }
        //校验用户
        User checkUser = userMapper.selectById(dto.getUserId());
        if (checkUser==null) {
            return Result.errorResult(Code.DATA_NOT_EXIST);
        }
        //构建user
        User user=new User();
        BeanUtils.copyProperties(checkUser,user);
        if (dto.getStudentId()!=null) {
            user.setStudentId(dto.getStudentId());
        }
        if (!dto.getPassword().equals("")) {
            String password = DigestUtils.md5Hex(checkUser.getUserSalt() + dto.getPassword());
            user.setUserPassword(password);
            user.setPassword(dto.getPassword());
        }
        //修改
        int checkUpdate = userMapper.updateById(user);
        //修改异常抛出
        if (checkUpdate==0) {
            return Result.errorResult(Code.SERVER_ERROR);
        }
        return Result.okResult(Code.SUCCESS);
    }
}




